package com.eling.elcms.system.service.impl;

import com.eling.elcms.community.event.DepartmentAfterSealUnSealEvent;
import com.eling.elcms.core.event.IEventListener;
import com.eling.elcms.core.exception.BusinessException;
import com.eling.elcms.core.service.impl.GenericManagerImpl;
import com.eling.elcms.privilege.model.Role;
import com.eling.elcms.privilege.service.IUserManager;
import com.eling.elcms.system.dao.IElcmsUserDao;
import com.eling.elcms.system.model.ElcmsUser;
import com.eling.elcms.system.service.IElcmsUserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Service
public class ElcmsUserManagerImpl extends GenericManagerImpl<ElcmsUser, Long> implements IElcmsUserManager {

	private IElcmsUserDao elcmsUserDao;

	@Autowired
	private IUserManager userManager; 
	
	@Autowired
    public void setElcmsUserDao(IElcmsUserDao dao) {
        this.dao = dao;
        this.elcmsUserDao = dao;
    }

	@Override
	public ElcmsUser save(ElcmsUser user) {
		// 对于新增用户，默认需要限制IP登陆
		if (null == user.getPkUser()) {
			user.setCheckLoginIp(true);
		}
		return (ElcmsUser) userManager.save(user);
	}

	@Override
	public List<ElcmsUser> queryUsersByBuilding(Long pkBuilding, Long pkRole) {
		return elcmsUserDao.queryUsersByBuilding(pkBuilding,pkRole);
	}
	
	@Override
	public List<ElcmsUser> queryUsersByRole(Role role) {
		// 只查询不具备1、2、7角色pk的用户
		ElcmsUser cond= new ElcmsUser();
		Set<Role> roles = new HashSet<>();
		roles.add(role);
		cond.setRoles(roles);
		List<ElcmsUser> users = super.query(cond);
	
		for (Iterator<ElcmsUser> it = users.iterator(); it.hasNext();) {
			ElcmsUser user = it.next();
			for (Role r : user.getRoles()) {
				int pkR = r.getPkRole().intValue();
				if ( pkR == 1 || pkR ==2 || pkR == 7) {
					it.remove();
					break;
				}
			}
		}
		return users;
	}
	
	@Service
	public static class DepartmentSealEventListener  implements IEventListener<DepartmentAfterSealUnSealEvent> {
		   
	    @Autowired
		IElcmsUserDao elcmsUserDao;
	    
		@Override
		public void doEvent(DepartmentAfterSealUnSealEvent event) {
			if(event.getDepartment().getSeal()){
				ElcmsUser elcmsuser = new ElcmsUser();
				elcmsuser.setDepartment((event.getDepartment()));
				List<ElcmsUser> users=elcmsUserDao.query(elcmsuser);
				String userNames="";
				if(users.size()==0){
					return;
				}
				for(int i = 0;i < users.size() && i<5 ; i++){
					 if(i>0){
						 userNames+="、";
					 }
					 userNames+=users.get(i).getCode();
				}
				if(users.size()>5){
					userNames+="...";
				}
				throw new BusinessException(event.getDepartment().getName()+" 在用户配置中被用户: ‘ "+userNames+" ’ 引用,不能被封存");
			}
			
		}
	}
}
